package com.zjf.carpark.interceptor;

import com.zjf.carpark.entities.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 方法执行前
     *
     * @param httpServletRequest
     * @param response
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o) throws Exception {

        System.out.println("--------拦截中-------");
        HttpSession session = httpServletRequest.getSession();

        User user = (User) session.getAttribute("user");

        System.out.println(user);
        if (user == null) {
            try {
                response.sendRedirect("/desk/login");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
